import 'package:bloc/bloc.dart'; //TODO study
import 'package:rxdart/subjects.dart';
import 'package:rxdart/rxdart.dart';//TODO study
import 'package:state_management_flutter_bloc/bloc/palyer_list_states.dart';
import 'package:state_management_flutter_bloc/bloc/player_listing_events.dart';
import 'package:state_management_flutter_bloc/models/api_models.dart';
import 'package:state_management_flutter_bloc/models/nation.dart';
import 'package:state_management_flutter_bloc/services/player_repository.dart';

class PlayerListingBloc extends Bloc<PlayerListingEvent, PlayerListingState> {
  final PlayerRepository playerRepository;
  PlayerListingBloc({this.playerRepository});
  NationModel _selectedNationModel;
  int currentPageIndex;
  int maxPages;
  List<Players> players = [];

  ///实现弹性搜索
  /* 0.8.0 版本写法
  @override
  Stream<PlayerListingEvent> transform(Stream<PlayerListingEvent> events) {
   // return super.transform(events);
    //return (events as PublishSubject<PlayerListingEvent>).transform(DebounceStreamTransformer(Duration(milliseconds: 200)));
    return super.transform((events as PublishSubject<PlayerListingEvent>).debounce(Duration(milliseconds: 250)),next);
  }
  */

  ///0.18.2
  @override
  Stream<PlayerListingState> transform(Stream<PlayerListingEvent> events, Stream<PlayerListingState> Function(PlayerListingEvent event) next) {
    return super.transform((events as PublishSubject<PlayerListingEvent>).debounceTime(Duration(milliseconds: 1000)),next);
  }

  @override
  PlayerListingState get initialState => PlayerUninitializedState();

  ///0.18.2版本
  @override
  Stream<PlayerListingState> mapEventToState(PlayerListingEvent event) async* {
    ApiResult result;
    try {
      if (event is CountrySelectedEvent) {
        _selectedNationModel = event.nationModel;
        currentPageIndex = event.page;
        yield PlayerFetchingState();
        result = await playerRepository.fetchPlayersByCountry(
            event.nationModel.countryId,
            page: event.page);
      } else if (event is PlayerListLoadMoreEvent) {
        yield PlayerListLoadingMoreState(players: players);
        if (currentPageIndex > maxPages) {
          currentPageIndex = maxPages;
        } else {
          currentPageIndex++;
        }
        result = await playerRepository.fetchPlayersByCountry(
            _selectedNationModel.countryId,
            page: currentPageIndex);
        players.addAll(result.items);
      } else if(event is SearchTextChangedEvent){
        yield PlayerFetchingState();
        result = await playerRepository.fetchPlayersByName(
            event.searchTerm,
            page: currentPageIndex);
      }else if(event is SearchAdvanceEvent){
        yield PlayerFetchingState();
        result = await playerRepository.fetchPlayersAdvanceSearch(event.searchConfiguration.selectedNations,
            event.searchConfiguration.selectedLeagues, event.searchConfiguration.selectedPositions);
      }
      players = result.items;
      maxPages = result.totalPages;
      if (players.length == 0) {
        yield PlayerEmptyState();
      } else {
        yield PlayerFetchedState(players: players);
      }
    } catch (_) {
      yield PlayerErrorState();
    }
  }


  //TODO 学习研究一下生成器函数
  /* 0.8.0 版本写法
  @override
  Stream<PlayerListingState> mapEventToState(
      PlayerListingState currentState, PlayerListingEvent event) async* {
    ApiResult result;
    try {
      if (event is CountrySelectedEvent) {
        _selectedNationModel = event.nationModel;
        currentPageIndex = event.page;
        yield PlayerFetchingState();
        result = await playerRepository.fetchPlayersByCountry(
            event.nationModel.countryId,
            page: event.page);
      } else if (event is PlayerListLoadMoreEvent) {
        yield PlayerListLoadingMoreState(players: players);
        if (currentPageIndex > maxPages) {
          currentPageIndex = maxPages;
        } else {
          currentPageIndex++;
        }
        result = await playerRepository.fetchPlayersByCountry(
            _selectedNationModel.countryId,
            page: currentPageIndex);
        players.addAll(result.items);
      } else if(event is SearchTextChangedEvent){
        yield PlayerFetchingState();
        result = await playerRepository.fetchPlayersByName(
            event.searchTerm,
            page: currentPageIndex);
      }
      players = result.items;
      maxPages = result.totalPages;
      if (players.length == 0) {
        yield PlayerEmptyState();
      } else {
        yield PlayerFetchedState(players: players);
      }
    } catch (_) {
      yield PlayerErrorState();
    }
  }
  */
}
